package com.ebanma.cloud.user.strategy;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ebanma.cloud.constant.RedisConstant;
import com.ebanma.cloud.dto.AjaxResult;
import com.ebanma.cloud.dto.UserDTO;
import com.ebanma.cloud.user.dao.mapper.UserMapper;
import com.ebanma.cloud.user.dao.po.User;
import com.ebanma.cloud.utils.JwtUtil;
import com.ebanma.cloud.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class PhoneStrategy extends BaseLoginStrategy {

    @Resource
    private JwtUtil jwtUtil;

    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public AjaxResult grant(UserDTO userDTO) {
        //根据手机查询user
        LambdaQueryWrapper<User> eq = new LambdaQueryWrapper<User>().eq(User::getPhone, userDTO.getPhone());
        User user=null;
        //登录验证码code正确，且该用户在db中存在
        if (!(redisUtil.get(RedisConstant.CAPTCHA_CODE+userDTO.getPhone())).equals(userDTO.getCode()) || ((user=userMapper.selectOne(eq))==null)){
            return AjaxResult.fail(401,"验证码不正确，请重试",null);
        }
        //登录成功，将user存入redis,返回token
        String uuid= RedisConstant.LOGIN_TOKEN+ UUID.fastUUID().toString(true);
        redisUtil.setEx(uuid, JSONUtil.toJsonStr(user),RedisConstant.LOGIN_TTL, TimeUnit.MINUTES);
        Map<String, String> payload = new HashMap<>(16);
        //封装user对应的uuid
        payload.put(RedisConstant.LOGIN_TOKEN, uuid);
        String jwtToken = jwtUtil.createJwtToken(payload, Calendar.HOUR, 8);

        HashMap<String, Object> res = new HashMap<>(16);
        res.put(RedisConstant.JWT_TOKEN,jwtToken);
        //返回给前端应该过滤掉敏感字段
        user.setPassword(null);
        res.put("user",user);
        //将验证码通过三方平台发给用户
        //TODO
        return AjaxResult.success(200, "登录成功", res);
    }
}
